#!/bin/sh

# Usage:
#    containers/flatpak/update-flathub [tarball] [flathub-repo]
#
# Both arguments are mandatory.  [tarball] is the (already built) tarball to be
# used for the flatpak.  [flatpak-repo] is a path to a directory with a clone
# of the flathub repository to update and push a branch on.
#
# If the URLBASE environment variable is set, it overrides the default value.

set -eu
cd "$(realpath -m "$0"/../../..)"

. containers/flatpak/prepare

# Arguments
TARBALL="$1"
FLATHUB_REPO="$2"

# Environment
URLBASE="${URLBASE:-https://github.com/cockpit-project/cockpit/releases/download}"

# Make sure we start from the expected state
test -f "${TARBALL}"
test -d "${FLATHUB_REPO}"
test -e "${FLATHUB_REPO}/.git"
test -z "$(git -C "${FLATHUB_REPO}" status --porcelain)"
test -f "${FLATHUB_REPO}/${FLATPAK_ID}.metainfo.xml"
test -f "${FLATHUB_REPO}/${FLATPAK_ID}.yml"

# Mine the previous versions out of the existing metainfo file
PREVIOUS_RELEASES="$(sed -n 's/^\(    <release .*\)$/\1\\n/p' "${FLATHUB_REPO}/${FLATPAK_ID}.metainfo.xml" | tr -d '\n')"

prepare "${TARBALL}" "${URLBASE}"

cp "${FLATPAK_ID}".metainfo.xml "${FLATHUB_REPO}"/
cp "${FLATPAK_ID}".yml "${FLATHUB_REPO}"/
cd "${FLATHUB_REPO}"

# Create a branch named after the version and push it to the origin
git checkout -b "${VERSION}"
git commit --message "Update to version ${VERSION}" --only \
    "${FLATPAK_ID}".metainfo.xml \
    "${FLATPAK_ID}".yml
